package com.javasm.controller.stockController;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.javasm.common.http.AxiosResult;
import com.javasm.common.page.PageResult;
import com.javasm.common.util.DownloadUtils;
import com.javasm.common.util.RedisDistUtil;
import com.javasm.controller.goodsController.GdProductController;
import com.javasm.domin.criteria.stockCtriteria.PutStorageCriteria;
import com.javasm.domin.criteria.stockCtriteria.PutStorageGoodsCriteria;
import com.javasm.domin.entity.goodsEntity.GdProduct;
import com.javasm.domin.entity.stockEntity.PutStorageGoods;
import com.javasm.domin.entity.stockEntity.PutStorageInfo;
import com.javasm.domin.vo.stockVo.PutStorageGoodsVo;
import com.javasm.domin.vo.stockVo.PutStorageInfoVo;
import com.javasm.mapper.stockMapper.PutStorageGoodsMapper;
import com.javasm.mapper.stockMapper.PutStorageImelMapper;
import com.javasm.mapper.stockMapper.PutStorageInfoMapper;
import com.javasm.service.stockService.PutStorageGoodsService;
import com.javasm.service.stockService.PutStorageImelService;
import com.javasm.service.stockService.PutStorageInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.*;

import static com.javasm.common.dictionary.InitContext.dicCache;

/**
 * @Author：zzt
 * @Version：1.0
 * @Date：2021/11/24-21:11
 * @Since:jdk1.8
 * @Description:
 */
@RestController
@RequestMapping("/putStorage")
@RequiredArgsConstructor
public class PutStorageController {
    private final PutStorageInfoService putStorageInfoService;
    private final PutStorageGoodsService putStorageGoodsService;
    private final PutStorageImelMapper putStorageImelMapper;
    private final PutStorageImelService putStorageImelService;
    @Resource
    private PutStorageGoodsMapper putStorageGoodsMapper;
    private final PutStorageInfoMapper putStorageInfoMapper;
    @Resource
    private GdProductController gdProductController;

    @RequestMapping("/dic")
    public AxiosResult<Map<String, LinkedHashMap<Integer, String>>> hello() {
        Map<String , LinkedHashMap<Integer, String>> payType = RedisDistUtil.transformTypeList("payType");
        return AxiosResult.success(dicCache);
    }


    @RequestMapping("purchaseInfo/{id}")
    public AxiosResult<PutStorageInfoVo> PurchaseInfo(@PathVariable Serializable id) {
        PutStorageInfo byId = putStorageInfoService.getById(id);
        PutStorageInfoVo putStorageInfoVo = new PutStorageInfoVo();
        BeanUtils.copyProperties(byId, putStorageInfoVo);
        return AxiosResult.success(putStorageInfoVo);
    }

    @RequestMapping("purchaseInfo")
    public AxiosResult<PageResult<PutStorageInfoVo>> purchaseInfo(PutStorageCriteria putStorageCriteria) {
        PageResult<PutStorageInfoVo> putStorageInfoVoPageResult = putStorageInfoService.selectPage(putStorageCriteria);
        return AxiosResult.success(putStorageInfoVoPageResult);
    }


    @RequestMapping("purchaseGoods")
    public AxiosResult<PageResult<PutStorageGoodsVo>> purchaseGoods(PutStorageGoodsCriteria putStorageGoodsCriteria) {
        PageResult<PutStorageGoodsVo> putStorageGoodsPageResult = putStorageGoodsService.findByIdGoods(putStorageGoodsCriteria);
        return AxiosResult.success(putStorageGoodsPageResult);
    }

    /**
     * 提交串号
     * @param imelList
     * @param imelId
     * @return
     */
    @RequestMapping("submitImel/{imelId}")
    public AxiosResult<String> purchaseGoods(@RequestBody String[] imelList,@PathVariable Integer imelId) {
        LinkedHashSet<String> hashSet = new LinkedHashSet(Arrays.asList(imelList));
        ArrayList<String> strings = new ArrayList<>(hashSet);
        for (int i = 0; i < strings.size(); i++) {
            if (putStorageImelMapper.findImelUnique(strings.get(i))>=1){
                strings.remove(strings.get(i));
                i=0;
            }
        }

//        putStorageImelMapper.findImelUnique()

        System.out.println(strings);

        for (String string : strings) {
            putStorageImelMapper.addImel(string, imelId);
        }

        return AxiosResult.success("提交串号成功");
    }

    @RequestMapping("updataIntoState/{id}")
    public AxiosResult<String> updataIntoState(@PathVariable Integer id){
        putStorageGoodsMapper.updataIntoState(id);

        return AxiosResult.success("更新录入标志");
    }

    //修改入库数量/{num}
    @RequestMapping("updateIdStorageNum/{id}")
    public  AxiosResult<String> updateIdAndPutStorageNum(@PathVariable Integer id){
        PutStorageGoods putStorageGoods = putStorageGoodsMapper.selectById(id);
        Integer putStorageImelId = putStorageGoods.getPutStorageImelId();
        putStorageGoodsMapper.updateIdAndPutStorageNum(id,putStorageImelMapper.findImelListById(putStorageImelId).size());
        return AxiosResult.success("更新录入数量成功");
    }


    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        StringBuilder buffer = new StringBuilder();
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<List<Object>> readAll = reader.read();
            reader.close();
            for (int i = 1; i < readAll.size(); i++) {
                if (i==readAll.size()-1){
                    buffer.append(readAll.get(i).get(0));
                }else {
                    buffer.append(readAll.get(i).get(0)).append("\n");
                }
            }
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "错误";
    }


    @GetMapping("/download")
    public String downloadFile(HttpServletResponse response) {
        return DownloadUtils.downloadFile(response, "C:\\Users\\Administrator\\Desktop\\导入串号模板.xls");
    }

    @RequestMapping("/findImelListById/{id}")
    public AxiosResult<String> findImelListById(@PathVariable Integer id){
        return AxiosResult.success(putStorageImelService.findImelListById(id));
    }

    //录入
    @RequestMapping("/findGoodsStatus/{id}")
    public AxiosResult<String> findAllByGoodsId(@PathVariable Integer id){
        List<PutStorageGoods> allByGoodsId = putStorageGoodsMapper.findAllById(id);
        for (PutStorageGoods putStorageGoods : allByGoodsId) {
            if (putStorageGoods.getIntoState()==0||putStorageGoods.getPurchaseNum()>putStorageGoods.getPutStorageNum()){
                return AxiosResult.success("查询剩余串号成功");
            }
        }
        //如果已录入则改为状态值
        putStorageInfoMapper.updatePurchaseStatusById(id);
        for (PutStorageGoods putStorageGoods : allByGoodsId) {
            GdProduct gdProduct = new GdProduct();
            gdProduct.setCreateTime(new Date());
            gdProduct.setTypeId(5);
            gdProduct.setBasicsDistribution("非铺货");
            gdProduct.setGoodsId(132661302);
            gdProduct.setBasicsPurchase("集团采购");
            gdProduct.setBasicsStandbyMachine("非备机");
            gdProduct.setBrandId(putStorageGoods.getGoodsId());
            gdProduct.setColourId(putStorageGoods.getProductColorId());
            gdProduct.setModelId(putStorageGoods.getProductName());
            gdProduct.setCreateBy("10001");
            gdProductController.save(gdProduct);
        }
        return AxiosResult.success("修改剩余串号成功");
    }

    @RequestMapping(value = "createBatchExcel/{ids}", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void batchExcel(HttpServletResponse response, @PathVariable List<Integer> ids) {
        putStorageInfoService.createBatchExcel(response, ids);
    }

}
